package com.hsj.acc;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;

import java.util.concurrent.TimeUnit;

/**
 * 配置文件热加载
 */
public class ConfigReloading {

    public static void main(String[] args) throws ConfigurationException, InterruptedException {
        PropertiesConfiguration pc = new PropertiesConfiguration("1.properties");

        pc.addConfigurationListener(event -> {
            if (!event.isBeforeUpdate() && event.getType() == PropertiesConfiguration.EVENT_RELOAD){
                System.out.println("配置文件加载...");
                pc.getKeys().forEachRemaining(k->{
                    System.out.println(k + "-->" + pc.getString(k));
                });
            }
        });

        FileChangedReloadingStrategy reloadingStrategy = new FileChangedReloadingStrategy();
        reloadingStrategy.setRefreshDelay(3000L);
        pc.setReloadingStrategy(reloadingStrategy);

        otherThreadGet(pc);

        Thread.sleep(100000L);
    }

    static void otherThreadGet(Configuration config){

        new Thread(() -> {
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                config.getString("common.name");
            }
        }).start();


    }

}
